package com.example.safeassistan.hiddendanger.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.safeassistan.R;
import com.example.safeassistan.base.BaseActivity;
import com.example.safeassistan.base.BaseModel;
import com.example.safeassistan.constants.UrlConstants;
import com.example.safeassistan.home.activity.AuthorizeDepartMentPerson;
import com.example.safeassistan.home.activity.AuthorizeDepartment;
import com.example.safeassistan.home.activity.HiddendangerReform;
import com.example.safeassistan.home.adapter.ImageListAdapter;
import com.example.safeassistan.http.HttpRequest;
import com.example.safeassistan.http.HttpStringCallBack;
import com.example.safeassistan.main.MainActivity;
import com.example.safeassistan.utile.GlideEngine;
import com.example.safeassistan.utile.JsonUtils;
import com.example.safeassistan.utile.ToastUtil;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class HiddendangerCheckAccept extends BaseActivity implements View.OnClickListener {
    private static final Integer REQUESTCODE=10000;
    private static final Integer REQUESTCODE2=10002;

    private TextView tvNoAuthorize,tvAuthorize,tvOk,tvNoOk,tvSubmit1,tvDepart,tvAuthorizor,
            tvHiddendDangerName;
    private LinearLayout llAuthorize,llNoAuthorize,llDepartment,llAuthorizer;
    private EditText etEntrustState,etAcceptIntro;
    private RecyclerView rcPic,rcHdangerImg;

    private String status="0";//是否委托 0 不委托 1委托
    private String state="";//验收说明
    private String result="1";// 1 已通过 0未通过
    private String hiddenId="";//隐患id
    private String entrustPerson="";//委托人员
    private String entrustDepart="";//委托部门
    private String accessory="";//验收附件
    private String hiddenName="";//隐患名称
    private String hdangerImg="";//隐患附件


    private HiddenDangerImageAdapter adapter;
    private ImageListAdapter adapters;
    private RecyclerView.LayoutManager managers;
    private ArrayList<String> imagesUrl;

    public static void actionStart(Context context,String hiddenId,String hiddenName,String hdangerImg) {
        Intent intent = new Intent(context, HiddendangerCheckAccept.class);
        intent.putExtra("hiddenId",hiddenId);
        intent.putExtra("hiddenName",hiddenName);
        intent.putExtra("hdangerImg",hdangerImg);
        context.startActivity(intent);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.tvNoAuthorize:
                //没有委托
                reSetAuthorize();
                status="0";
                tvNoAuthorize.setBackgroundResource(R.drawable.stoke_solid_blue_bg_5);
                tvNoAuthorize.setTextColor(getResources().getColor(R.color.blue_3B5BEA));
                llNoAuthorize.setVisibility(View.VISIBLE);
                llAuthorize.setVisibility(View.GONE);
                break;
            case R.id.tvAuthorize:
                //委托
                reSetAuthorize();
                status="1";
                tvAuthorize.setBackgroundResource(R.drawable.stoke_solid_blue_bg_5);
                tvAuthorize.setTextColor(getResources().getColor(R.color.blue_3B5BEA));
                llNoAuthorize.setVisibility(View.GONE);
                llAuthorize.setVisibility(View.VISIBLE);
                break;
            case R.id.tvNoOk:
                //不通过
                reSetResult();
                result="0";
                etAcceptIntro.setText("不合格");
                etEntrustState.setText("不合格");
                state="不合格";
                tvNoOk.setTextColor(getResources().getColor(R.color.blue_3B5BEA));
                tvNoOk.setBackgroundResource(R.drawable.stoke_solid_blue_bg_5);
                break;
            case R.id.tvOk:
                //通过
                result="1";
                etAcceptIntro.setText("合格");
                etEntrustState.setText("合格");
                state="合格";
                reSetResult();
                tvOk.setTextColor(getResources().getColor(R.color.blue_3B5BEA));
                tvOk.setBackgroundResource(R.drawable.stoke_solid_blue_bg_5);
                break;
            case R.id.llDepartment:
                //委托部门
                Intent intent=new Intent(HiddendangerCheckAccept.this, AuthorizeDepartment.class);
                intent.putExtra("flag", REQUESTCODE);
                startActivityForResult(intent, REQUESTCODE);
                break;
            case R.id.llAuthorizer:
                //委托人
                if (entrustDepart.equals("")){
                    Toast.makeText(HiddendangerCheckAccept.this,"请先选择部门！！",Toast.LENGTH_SHORT).show();
                }else {
                    Intent intent3=new Intent(HiddendangerCheckAccept.this, AuthorizeDepartMentPerson.class);
                    intent3.putExtra("flag", REQUESTCODE2);
                    intent3.putExtra("defectId",entrustDepart);
                    startActivityForResult(intent3, REQUESTCODE2);
                }
                break;
            case R.id.tvSubmit1:
                if (status.equals("1")){
                    //委托了
                    submitData();
                }else {
                    if (accessory.length()<1){
                        if (imagesUrl.size()<=0){
                            Toast.makeText(HiddendangerCheckAccept.this,"请至少上传一张附件！！",Toast.LENGTH_SHORT).show();
                            return;
                        }else {
                            uploadImg(imagesUrl.get(0));
                        }
                    }else {
                        submitData();
                    }
                }
                break;
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode==RESULT_OK){
            if (requestCode==REQUESTCODE){
                //委托部门
                entrustDepart=data.getStringExtra("id");
                tvDepart.setText(data.getStringExtra("name"));
            }else if(requestCode==REQUESTCODE2){
                //委托人
                entrustPerson=data.getStringExtra("id");
                tvAuthorizor.setText(data.getStringExtra("name"));
            }else if (requestCode== PictureConfig.CHOOSE_REQUEST) {
                // 结果回调
                //获取oss  token
                List<LocalMedia> cameraList = PictureSelector.obtainMultipleResult(data);
                imagesUrl.clear();
                for (int i = 0; i < cameraList.size(); i++) {
                    imagesUrl.add(cameraList.get(i).getRealPath());
//                    if (imagesUrl.size() == 3) {
//                        break;
//                    }
                }
                adapter.notifyDataSetChanged();
            }
        }
    }

    @Override
    protected void init(Bundle savedInstanceState) {
        setAndroidNativeLightStatusBar(true);
    }

    @Override
    protected int setLayoutResourceID() {
        return R.layout.hiddendanger_checkaccept;
    }

    @Override
    protected void initView() {
        setTitleText("隐患验收");
        hiddenId=getIntent().getStringExtra("hiddenId");
        hiddenName=getIntent().getStringExtra("hiddenName");
        hdangerImg=getIntent().getStringExtra("hdangerImg");
        tvAuthorize=findViewById(R.id.tvAuthorize);
        tvAuthorize.setOnClickListener(this::onClick);
        tvNoAuthorize=findViewById(R.id.tvNoAuthorize);
        tvNoAuthorize.setOnClickListener(this::onClick);
        llNoAuthorize=findViewById(R.id.llNoAuthorize);
        tvSubmit1=findViewById(R.id.tvSubmit1);
        tvDepart=findViewById(R.id.tvDepart);
        llAuthorize=findViewById(R.id.llAuthorize);
        tvAuthorizor=findViewById(R.id.tvAuthorizor);
        tvNoOk=findViewById(R.id.tvNoOk);
        etAcceptIntro=findViewById(R.id.etAcceptIntro);
        rcHdangerImg=findViewById(R.id.rcHdangerImg);
        tvHiddendDangerName=findViewById(R.id.tvHiddendDangerName);
        tvNoOk.setOnClickListener(this::onClick);
        tvOk=findViewById(R.id.tvOk);
        tvOk.setOnClickListener(this::onClick);
        etEntrustState=findViewById(R.id.etEntrustState);
        llDepartment=findViewById(R.id.llDepartment);
        llDepartment.setOnClickListener(this::onClick);
        llAuthorizer=findViewById(R.id.llAuthorizer);
        rcPic=findViewById(R.id.rcPic);
        tvSubmit1.setOnClickListener(this::onClick);
        llAuthorizer.setOnClickListener(this::onClick);
        tvHiddendDangerName.setText(hiddenName);
        etEntrustState.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) { }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                state=s.toString().trim();
            }

            @Override
            public void afterTextChanged(Editable s) { }
        });
        etAcceptIntro.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                state=s.toString().trim();
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        etAcceptIntro.setText("合格");
        etEntrustState.setText("合格");
        state="合格";


        imagesUrl=new ArrayList<>();
        managers=new GridLayoutManager(getContext(),3);
        rcPic.setLayoutManager(managers);
        adapter=new HiddenDangerImageAdapter(imagesUrl, HiddendangerCheckAccept.this);
        rcPic.setHasFixedSize(true);
        rcPic.setAdapter(adapter);
        adapter.setClickListener(new HiddenDangerImageAdapter.OnItemClickListener() {
            @Override
            public void onClick(View view, int position) {
                //添加
                PictureSelector
                        .create(HiddendangerCheckAccept.this)
                        .openGallery(PictureMimeType.ofImage())
                        .selectionMode(PictureConfig.MULTIPLE)
                        .isCamera(true)
                        // .selectionData(imagesUrl)
                        // .maxSelectNum(3)
                        .compressQuality(100)
                        .loadImageEngine(GlideEngine.createGlideEngine())
                        .forResult(PictureConfig.CHOOSE_REQUEST);
            }

            @Override
            public void onSelected(View view, int position) {
                switch (view.getId()){
                    case R.id.ivClear:
                        //删除当前图片
                        imagesUrl.remove(position);
                        adapter.notifyDataSetChanged();
                        break;
                }
            }
        });

        if (hdangerImg!=null&&hdangerImg.length()>0) {
            String strs []=hdangerImg.split(",");
            ArrayList<String> lists=new ArrayList<>();
            for (int i=0;i<strs.length;i++){
                if (strs[i].length()>1){
                    lists.add(strs[i]);
                }
            }
            rcHdangerImg.setLayoutManager(new GridLayoutManager(HiddendangerCheckAccept.this,3,RecyclerView.VERTICAL,false));
            adapters=new ImageListAdapter(lists);
            rcHdangerImg.setHasFixedSize(true);
            rcHdangerImg.setAdapter(adapters);
        }
    }

    public void uploadImg(String path){
        new HttpRequest(HiddendangerCheckAccept.this).doUploadFile(UrlConstants.commonupload, "", "file", new File(path), new HttpStringCallBack() {
            @RequiresApi(api = Build.VERSION_CODES.M)
            @Override
            public void onSuccess(Object result) {
                String datas = result.toString();
                JSONObject jsonObject = null;
                try {
                    jsonObject = new JSONObject(datas);
                    String message = jsonObject.getString("message");
                    Boolean success = jsonObject.getBoolean("success");
                    if (success) {
                        Object obj = JsonUtils.fromJson(result.toString(), BaseModel.class);
                        if (obj instanceof BaseModel) {
                            BaseModel model=(BaseModel) obj;
                            imagesUrl.remove(0);
                            accessory=accessory+model.getMessage()+",";
                            Iterator<String> iterator=imagesUrl.iterator();
                            if (iterator.hasNext()){
                                uploadImg(iterator.next());
                            }else {
                                submitData();
                            }
                        }else {
                            ToastUtil toastUtil = new ToastUtil(getContext(), R.layout.popu_success1, message, 1);
                            toastUtil.show();
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(int code, String msg) { }
        });
    }


    public void submitData(){
        JSONObject jsonObject=new JSONObject();
        try {
            jsonObject.put("hiddenId",hiddenId);//隐患id
            jsonObject.put("status",status);//是否委托
            jsonObject.put("state",state);//说明
            jsonObject.put("result",result);//结果
            //委托人
            if (!entrustPerson.equals("")){
                jsonObject.put("entrustPerson",entrustPerson);
            }
            //委托部门
            if (!entrustDepart.equals("")){
                jsonObject.put("entrustDepart",entrustDepart);
            }

            //验收附件
            if (!accessory.equals("")){
                jsonObject.put("accessory",accessory.substring(0,accessory.length()-1));
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

        new HttpRequest(this).doPost(UrlConstants.dangeraccept, null,jsonObject, new HttpStringCallBack() {
            @RequiresApi(api = Build.VERSION_CODES.M)
            @Override
            public void onSuccess(Object result) {
                String datas = result.toString();
                JSONObject jsonObject = null;
                try {
                    jsonObject = new JSONObject(datas);
                    String message = jsonObject.getString("message");
                    Boolean success = jsonObject.getBoolean("success");
                    if (success) {
                        Object obj = JsonUtils.fromJson(result.toString(), BaseModel.class);
                        if (obj instanceof BaseModel) {
                            BaseModel model=(BaseModel) obj;
                            MainActivity.actionStart(HiddendangerCheckAccept.this,2);
                            finish();
                        }
                    }else {
                        Toast.makeText(HiddendangerCheckAccept.this,message,Toast.LENGTH_SHORT).show();
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(int code, String msg) { }
        });
    }

    public void reSetAuthorize(){
        tvNoAuthorize.setBackgroundResource(R.drawable.stoke_gray_bg_5);
        tvAuthorize.setBackgroundResource(R.drawable.stoke_gray_bg_5);
        tvNoAuthorize.setTextColor(getResources().getColor(R.color.gray9));
        tvAuthorize.setTextColor(getResources().getColor(R.color.gray9));
    }

    public void reSetResult(){
        tvOk.setTextColor(getResources().getColor(R.color.gray9));
        tvNoOk.setTextColor(getResources().getColor(R.color.gray9));
        tvNoOk.setBackgroundResource(R.drawable.stoke_gray_bg_5);
        tvOk.setBackgroundResource(R.drawable.stoke_gray_bg_5);
    }
    @Override
    protected void initData() {

    }

    @Override
    protected int getTitleBarType() {
        return 0;
    }
}
